package web.kx;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import org.apache.log4j.Logger;
import org.apache.log4j.xml.DOMConfigurator;
import org.htmlparser.util.ParserException;

public class Main {
	private Timer timer;
	private WapParser wapParser;
	private String[] cookerList;
	private String[] orderids;
	// static String CLEAN_COOK =
	// "http://wap.kaixin001.com/cafe/cook.php?clean=1&cafeid=ZZZZ&orderid=XXXXX&dishid=YYYYY&verify=3938990_3938990_1268707744_7af989040970ab6b1c591bd2101ce9ea_kx";
	// static String MOVING =
	// "http://wap.kaixin001.com/cafe/dish2counter.php?foodnum=550&cafeid=ZZZZ&orderid=XXXXX&verify=3938990_3938990_1268707717_7b6a35984bb8b3b7f2cbf312044170c0_kx&url=%2Fcafe%2Findex.php%3Fverify%3D3938990_3938990_1268700023_90e4c217fe4c0c8f1b3407193bfb2887_kx";
	static String CLEAN_COOK = "http://wap.kaixin001.com/cafe/cook.php?clean=1&cafeid=ZZZZ&orderid=XXXXX&dishid=YYYYY";
	static String MOVING = "http://wap.kaixin001.com/cafe/dish2counter.php?foodnum=550&cafeid=ZZZZ&orderid=XXXXX";
	private String cafeid;
	private long endTime;
	static {
		DOMConfigurator.configure("./GlobalCfg/log4j.xml");
	}
	public static Logger logger = Logger.getLogger("Schedule");
	static {
		try {
			InetAddress address = InetAddress.getLocalHost();
			if (address.toString().startsWith("192.168")) {

			} else {
				System.getProperties().put("proxySet", "true");
				System.getProperties().put("proxyHost", "15.105.253.234");
				System.getProperties().put("proxyPort", "8080");
			}
		} catch (UnknownHostException e) {
			logger.error(e);
		}
	}

	public Main(String username, String passwd) {
		timer = new java.util.Timer();
		wapParser = new WapParser();
		String[] click = wapParser.clickFilterPost(
				"http://wap.kaixin001.com/home/", "组件", "email=" + username
						+ "&" + "password=" + passwd + "&"
						+ "remember=1&from=&refuid=0&refcode=&login=提交");

		String[] clickFilter = wapParser.clickFilter(
				"http://wap.kaixin001.com/cafe/index.php", "移至餐台");
		if (clickFilter != null)
			for (int i = 0; i < clickFilter.length; i++) {
				wapParser.clickWithCheck(clickFilter[i], "移至");
			}

		clickFilter = wapParser.clickFilter(
				"http://wap.kaixin001.com/cafe/index.php", "清洁");
		if (clickFilter != null)
			for (int i = 0; i < clickFilter.length; i++) {
				wapParser.clickWithCheck((clickFilter[i]), "完成");
			}

		cookerList = wapParser.clickFilter(
				"http://wap.kaixin001.com/cafe/index.php", "做菜");
		if (null == cookerList || 0 == cookerList.length) {
			System.exit(1);
		}
		orderids = new String[cookerList.length];
		int indexOf = cookerList[0].indexOf("cafeid=");
		int indexEnd = cookerList[0].indexOf("&", indexOf);
		cafeid = cookerList[0]
				.substring(indexOf + "cafeid=".length(), indexEnd);
		logger.info("cafeid:" + cafeid);
		for (int i = 0; i < cookerList.length; i++) {
			String s = cookerList[i];
			indexOf = s.indexOf("orderid=");
			indexEnd = s.indexOf("&", indexOf);
			orderids[i] = s.substring(indexOf + "orderid=".length(), indexEnd);
			logger.info("orderids[" + i + "]:" + orderids[i]);
		}

	}

	public void startCook(String dish, int mins) {
		for (int i = 0; i < orderids.length; i++) {
			addACooker(i, orderids[i], dish, mins);

		}
	}

	public void startCook(Dish x) {
		for (int i = 0; i < orderids.length; i++) {
			addACooker(i, orderids[i], x.id + "", x.time);
		}
	}

	int pos = 0;

	public void startCook(Dish x, int count) {

		for (int i = 0; pos < orderids.length && i < count; pos++, i++) {
			addACooker(pos, orderids[pos], x.id + "", x.time);
		}
	}

	public void startCook(int id, int mins, int count) {

		for (int i = 0; pos < orderids.length && i < count; pos++, i++) {
			addACooker(pos, orderids[pos], id + "", mins);
		}
	}

	public static void main(String ss[]) throws Exception {

		DOMConfigurator.configure("./GlobalCfg/log4j.xml");
		String del=Config.getProperty("延迟启动");
		if(del!=null&&!del.equals("")) {
			int d = Integer.parseInt(del);
			Thread.sleep(d*60*1000);
		}
		final Main schdule = new Main(Config.getProperty("用户"), Config
				.getProperty("密码"));
		schdule.startCook(Dish.get(Config.getProperty("菜")), Integer
				.parseInt(Config.getProperty("个数")));
		schdule.startCook(Dish.get(Config.getProperty("菜2")), Integer
				.parseInt(Config.getProperty("个数2")));
//		arraTimerTask(schdule, Dish.get(Config.getProperty("菜")), Integer
//				.parseInt(Config.getProperty("个数")));
//		arraTimerTask(schdule, Dish.get(Config.getProperty("菜2")), Integer
//				.parseInt(Config.getProperty("个数2")));
	}

	private static void arraTimerTask(final Main schdule, final Dish x,
			final int count) {
		for (int i = 0; i < count; i++) {
			schdule.timer.schedule(new TimerTask() {
				@Override
				public void run() {
					schdule.startCook(x, 1);
				}
			}, x.time * 60 * 1000 / (count) * i);
		}
	}

	private void setWorkingTime(int i) {
		endTime = System.currentTimeMillis() + i * 60 * 60 * 1000;
		timer.schedule(new TimerTask() {

			@Override
			public void run() {
				needToEnd = true;

			}
		}, i * 60 * 60 * 1000);
	}

	int DELAY = 3000;
	boolean needToEnd = false;
	final java.util.Random random = new java.util.Random();

	protected void addACooker(final int pos, final String order,
			final String dish, final int mins, final int times) {
		final WapParser wapParser1 = wapParser;
		final TimerTask timerTask2 = new TimerTask() {
			int count = 0;
			WapParser wp = wapParser1;
			int thiscount = times;

			@Override
			public void run() {
				while (thiscount-- > 0) {
					logger.info("schdule pos" + pos + " count " + ++count
							+ " order " + order);
					wp.click(CLEAN_COOK.replaceAll("ZZZZ", cafeid).replaceAll(
							"XXXXX", order).replaceAll("YYYYY", dish));
					try {
						Thread.sleep(mins * 60 * 1000 + DELAY);
					} catch (InterruptedException e) {
						logger.error(e);
					}
					wp.click(MOVING.replaceAll("ZZZZ", cafeid).replaceAll(
							"XXXXX", order).replaceAll("YYYYY", dish));
				}
			}
		};
		new Thread(timerTask2).start();
	}

	protected void addACooker(final int pos, final String order,
			final String dish, final int mins) {
		this.addACooker(pos, order, dish, mins, Integer.MAX_VALUE);
	}

	protected void addMonitor(final int mins) {
		final TimerTask timerTask2 = new TimerTask() {

			@Override
			public void run() {
				wapParser.click("http://wap.kaixin001.com/cafe/index.php");
				if (needToEnd) {
					this.cancel();
				}
			}
		};
		timer.schedule(timerTask2, 0, DELAY + mins * 60 * 1000);
	}
}
